package com.zn.task;

import com.alibaba.fastjson.JSONObject;
import com.zn.entity.AppCustomer;
import com.zn.entity.FutureReportOrder;
import com.zn.entity.OptionTradingContract;
import com.zn.mapper.AppCustomerMapper;
import com.zn.mapper.FutureReportOrderMapper;
import com.zn.service.DocumentaryTradeService;
import com.zn.service.OptionTradeService;
import com.zn.socket.SocketHandler;
import com.zn.util.CSocketInfo;
import com.zn.util.Constant;
import com.zn.util.DateUtils;
import com.zn.vo.OptionSymbol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author YinJiaWei
 * @version 2018/8/24 13:38
 */
@Component
public class CheckOrderRefTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(CheckOrderRefTask.class);
    @Autowired
    private FutureReportOrderMapper futureReportOrderMapper;
    @Autowired
    OptionTradeService optionTradeService;
    @Autowired
    DocumentaryTradeService documentaryTradeService;
    private ExecutorService pool = Executors.newCachedThreadPool();


    //每天的凌晨3点 16点执行一次
    @Scheduled(cron="0 30 15 * * ?")
    public void executeNoResponseOrder(){
        try{
            /**查询未得到c++回报的订单**/
            List<FutureReportOrder> futureReportOrderList=futureReportOrderMapper.selectNotRespCStatus();
            for(FutureReportOrder futureReportOrder:futureReportOrderList){
                doExecuteNoResponseOrder(futureReportOrder);
            }
            /**查询创建时间为当天且收到响应且成交数量 < 委托数量**/
            List<FutureReportOrder> unfinishedOrderList=futureReportOrderMapper.selectCancelNeedOrderInfo();
            for(FutureReportOrder futureReportOrder:unfinishedOrderList){
                doExecuteUnfinishedOrder(futureReportOrder);
            }
        }catch (Exception e){
            LOGGER.error("CheckOrderRefTask Error ..............:" , e);
        }
    }

    /**
     * 执行未响应的订单
     * @param futureReportOrder
     */
    private void doExecuteNoResponseOrder(FutureReportOrder futureReportOrder){
        pool.execute(new Thread(() -> {
            try {
                /**模拟错单报单响应**/
                /**report|交易日|报单提交状态|报单状态|报单编号|报单来源|报单类型|数量|最小成交量|今成交数量|报单价格|本地报单编号|合约|状态信息|报单时间|错误ID**/
                /**report|20190219|0|5||0|0|5|1|0|0.0000|e190219100204|10001675||13:47:17|31||**/
                Integer volume=futureReportOrder.getVolume();
                BigDecimal limitPrice=futureReportOrder.getLimitPrice();
                String orderRef=futureReportOrder.getOrderRef();
                String instrumentCode=futureReportOrder.getInstrumentCode();
                String tradeDay= DateUtils.getDateTime("yyyyMMdd", new Date());
                String tradeTime=DateUtils.getDateTime("HH:mm:ss", new Date());
                String respReport="report|"+tradeDay+"|0|99||0|0|"+volume+"|1|0|"+limitPrice+"|"+orderRef+"|"+instrumentCode+"|平台无响应订单定时结算|"+tradeTime+"|a200|0|0|";
                optionTradeService.respReportOrder(respReport);
            }catch (Exception e){
                LOGGER.error("doExecuteNoResponseOrder------->",e);
            }

        }));
    }

    /**
     * 执行未终结订单进行挂单撤单结算
     * @param futureReportOrder
     */
    private void doExecuteUnfinishedOrder(FutureReportOrder futureReportOrder){
       pool.execute(new Thread(()->{
           try {
               String [] orderStatusAry=futureReportOrder.getOrderStatus().split("\\|");
               String lastOrderStatus=orderStatusAry[orderStatusAry.length-1];
               Integer volume=futureReportOrder.getVolume(),minVolume=futureReportOrder.getMinVolume(),tradingVolume=futureReportOrder.getTradeVolume();
               BigDecimal limitPrice=futureReportOrder.getLimitPrice();
               String orderRef=futureReportOrder.getOrderRef();
               String instrumentCode=futureReportOrder.getInstrumentCode();
               String tradeTime=DateUtils.getDateTime("HH:mm:ss", new Date());
               String tradeDay=futureReportOrder.getTradingDay();
               String orderSysId=futureReportOrder.getOrderSysId();
               /**客户信息不等于空 最后状态不等于全部成交 不等于错单 不等于撤单 不等于（交易程序来自qwin 并且最后状态等于a）**/
               if(!"0".equals(lastOrderStatus) && !"99".equals(lastOrderStatus) && !"5".equals(lastOrderStatus) && !("3".equals(futureReportOrder.getTradeServerCode()) && "a".equals(lastOrderStatus))){
                   /**report|交易日|报单提交状态|报单状态|报单编号|报单来源|报单类型|数量|最小成交量|今成交数量|报单价格|本地报单编号|合约|状态信息|报单时间|错误ID**/
                   String respReport="report|"+tradeDay+"|3|5|"+orderSysId+"|0|0|"+volume+"|"+minVolume+"|"+tradingVolume+"|"+limitPrice+"|"+orderRef+"|"+instrumentCode+"|平台挂单定时结算撤单|"+tradeTime+"|0|0|0|";
                   if("0".equals(futureReportOrder.getOrderType())){
                       /**普通报单**/
                       optionTradeService.respReportOrder(respReport);
                   }else if("1".equals(futureReportOrder.getOrderType())){
                       /**对冲单**/
                       optionTradeService.respHedgingReportOrder(respReport);
                   }else if("2".equals(futureReportOrder.getOrderType())){
                       /**跟单**/
                       documentaryTradeService.respDocumentaryReportOrder(respReport);
                   }
                   LOGGER.info(futureReportOrder.getOrderType()+"---doExecuteUnfinishedOrder dataInfo-->" + respReport);
               }else{
                   LOGGER.info("doExecuteUnfinishedOrder Check failed-------------->"+futureReportOrder.getOrderRef());
               }
           }catch (Exception e){
               LOGGER.error("doExecuteUnfinishedOrder------->",e);
           }

       }));
    }

}
